package com.lp.multi.juc.collection;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: lp
 * @create: 2021-06-27 17:48
 * @description: 读写锁、独占锁、排它锁
 * 读-读：共享
 * 读-写：只能写
 * 写-写：一个写
 * 缓存：写的时候其他线程不能写，也不能读；读的时候，其他线程可以读
 */
public class ReentrantReadWriteLockTest {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        //5个线程写
        for (int i = 0; i < 5; i++) {
            final int temp =i;
            new Thread(()->{
                myCache.put(String.valueOf(temp),String.valueOf(temp));
            }).start();
        }

        //5个线程读
        for (int i = 0; i < 5; i++) {
            final int temp =i;
            new Thread(()->{
                myCache.get(String.valueOf(temp));
            }).start();
        }
    }

}


class MyCache{
    //TODO volatile作用
    private volatile Map<String,String> cacheMap = new HashMap<String,String>();

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public boolean put(String key,String value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"存入key="+key+" value="+value);
            cacheMap.put(key,value);
            System.out.println(Thread.currentThread().getName()+"存入key成功");
            return true;
        }finally {
            lock.writeLock().unlock();
        }
    }

    public String get(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"取出key="+key+"对象");
            String value = cacheMap.get(key);
            System.out.println(Thread.currentThread().getName()+"取出成功key="+key+"value="+value);
            return value;
        }finally {
            lock.readLock().unlock();
        }
    }

}